package org.vaadinpa.data.serializer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.vaadinpa.data.Universe;
import org.vaadinpa.gui.VaadinPA;
import org.vaadinpa.logic.Command;
import org.vaadinpa.logic.Ticker;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class PASerializer {

	private static final String EXTENSION = ".pa";
	private static final String PATH = "c:\\temp\\PA\\";

	public static void serialize() throws IOException {

		FileWriter fw = new FileWriter(getFile());
		String xml = Universe.instance.serialize();
		xml = escape(xml);
		fw.write(xml);
		fw.close();
	}

	private static String escape(String xml) {
		return xml.replaceAll("<b>", "&lt;b&gt;").replaceAll("</b>", "&lt;/b&gt;");
	}

	private static File getFile() throws IOException {

		File f = new File(PATH + VaadinPA.SERVER_INSTANCE_ID + "_" + Ticker.currentTick + EXTENSION);
		if (!f.exists()) {
			f.createNewFile();
		}

		return f;
	}

	public static void parse() throws SAXException, ParserConfigurationException, IOException {
		File f = new File(PATH + "4c8ec34a-9d28-44dc-b9f6-757fcac90779_7.xml");

		Universe universe = new Universe();
		int currentTick = -1;
		String serverId = null;
		List<Command> commands = new LinkedList<Command>();

		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
		Node universeNode = doc.getFirstChild();
		Node firstLevelChild = universeNode.getFirstChild();
		do {

			if (firstLevelChild == null) {
				continue;
			}
			if (firstLevelChild.getNodeName().equals("#text")) {
				continue;
			}

			if (firstLevelChild.getNodeName().equals("tick")) {
				currentTick = Integer.parseInt(firstLevelChild.getTextContent());
			}
			if (firstLevelChild.getNodeName().equals("serverID")) {
				serverId = firstLevelChild.getTextContent();
			}

			if (firstLevelChild.getNodeName().equals("planets")) {
				parsePlanets(firstLevelChild, universe);
			}
			if (firstLevelChild.getNodeName().equals("battles")) {
				parseBattles(firstLevelChild, universe);
			}
			if (firstLevelChild.getNodeName().equals("commands")) {
				parseCommands(firstLevelChild, commands);
			}

		} while ((firstLevelChild = firstLevelChild.getNextSibling()) != null);

		System.out.println();

	}

	private static void parseBattles(Node battles, Universe universe) {

	}

	private static void parsePlanets(Node planets, Universe universe) {

	}

	private static void parseCommands(Node commands, List<Command> commands2) {

	}
}
